﻿window.MyCart = Backbone.Model.extend({
    urlRoot: 'api/shoppingcart/',
    url: function () {
        return this.urlRoot;
    }
});

window.MyCartList = Backbone.Collection.extend({
    model: MyCart,
    urlRoot: 'api/shoppingcart/',
    url: function () {
        return this.urlRoot + pageView.getCookieValue('uid');
    },
    parse: function (list) {
        _.each(list, function (model) {
            model['DiffPrice'] = model['MarketPrice'] - model['BuyPrice'];
        });
        return list;
    }
});

window.MyCartView = Backbone.View.extend({
    el: "#jqt",
    initialize: function () {
        this.collection = new MyCartList();
        this.template = $('#MyCartTemplate').html();
    },
    events: {
        'click #goShopping,.backShopping': 'goShopping',
        'click #MyCart .p-amount .add,#MyCart .p-amount .redu': 'changeProductCount',
        'change .productcount': 'updateProductCount',
        'click #MyCart .p-amount .delete': 'deleteFromCart',
        'click #MyCart li .p-img,#MyCart li .p-name': 'renderProductDetail',
        'click #MyCart #ordering': 'checkOrder'
    },
    render: function () {
        var partial = { header: $('#HeaderTemplate').html(), footer: $('#FooterTemplate').html(),
            innerFooter: $('#InnerFooterTemplate').html()
        };

        var data = { title: '购物车', btnListR: [{ name: 'sort' }, { name: 'cart' }, { name: 'home'}] };

        this.$el.append(Mustache.render(this.template, data, partial));

        this.fetchCarts();

        return this;

    },

    fetchCarts: function () {
        var that = this,
            loginId = localStorage.getItem('loginId'),
            template = $('#CartContentTemplate').html(),
            data,
            partial = { cartTemplate: $('#NoEmptyCartTemplate').html(), emptyCartTemplate: $('#EmptyCartTemplate').html() };
        that.collection.fetch({
            success: function () {
                var carts = that.collection.toJSON();
                if (carts == null || carts.length == 0) {
                    data = { hasCart: false };
                    localStorage.setItem('hasCarts', false);
                } else {
                    localStorage.setItem('hasCarts', true);
                    localStorage.setItem('cartItems', JSON.stringify(carts));
                    var count = 0, allPrice = 0.0;
                    _.each(carts, function (cart) {
                        count += +cart['BuyNumber'];
                        allPrice += (+cart['BuyNumber']) * (+cart['BuyPrice']);
                    });
                    data = { hasCart: true, mycarts: carts, count: count, allPrice: allPrice };
                    localStorage.setItem('allPrice', allPrice);
                }
                $('#cartContent').html(Mustache.render(template, data, partial));
                pageView.changeCartIcon();
                pageView.resizeScroll();
            }
        });
    },

    changeProductCount: function (e) {
        var target = $(e.currentTarget),
            that = this,
            count,
            tagName = target[0].tagName.toLowerCase(),
            productid = target.closest('li').attr('productid'),
            price = +target.closest('li').find('.pro-price').text(),
            type = target.hasClass('add') ? 'add' : 'reduce',
            input = target.siblings('input.productcount');

        var currentCount = +input.val();
        if (type === 'add') {
            input.val(currentCount + 1);
            count = 1;
        }
        else {
            if (currentCount == 1) return;
            input.val(currentCount - 1);
            count = -1;
        }
        window.setTimeout(function () {
            MyCartView.addToCarts(productid, price, count, function () {
                that.fetchCarts();
            });
        }, 300);
    },

    updateProductCount: function (e) {
        var target = $(e.currentTarget),
            that = this,
            productid = target.closest('li').attr('productid'),
            count = +target.val();
        if (isNaN(count)) return;
        if (count < 1) { this.deleteFromCart(e); return; }
        window.setTimeout(function () {
            MyCartView.UpdateToCarts(productid, count, function () {
                that.fetchCarts();
            });
        }, 300);

    },

    deleteFromCart: function (e) {
        var that = this,
            target = $(e.currentTarget),
            productid = target.closest('li').attr('productid');
        MyCartView.deleteProduct(productid, function () { that.fetchCarts(); });
    },

    goShopping: function () {
        pageView.goTo('FirstCategory');
    },

    renderProductDetail: function (e) {
        var target = $(e.currentTarget),
            productid = target.closest('li').attr('productid'),
            price = target.closest('li').find('span.pro-price').text();
        localStorage.setItem('productid', productid);
        localStorage.setItem('productDetail', JSON.stringify({ productid: productid, price: price }));
        pageView.goTo('ProductDetail');
    },
    checkOrder: function () {
        localStorage.removeItem('couponitem');
        pageView.goTo('OrderMake');
    }
}, {
    addToCarts: function (productid, price, count, callback) {
        var cart = new MyCart();
        cart.set({
            MemLoginID: pageView.getCookieValue('uid'),
            ProductGuid: productid,
            BuyNumber: +count,
            BuyPrice: +price,
            Attributes: '白色',
            ExtensionAttriutes: 'M'
        });
        cart.save('', '', {
            success: function (mdoel, res) {
                if (res && res == 202) {
                    callback.call();
                }
            }
        });
    },

    UpdateToCarts: function (productid, count, callback) {
        var cart = new MyCart();
        cart.set({
            id: 1,
            MemLoginID: pageView.getCookieValue('uid'),
            ProductGuid: productid,
            BuyNumber: +count,
            Attributes: '白色',
            ExtensionAttriutes: 'M'
        });
        cart.save('', '', {
            success: function (mdoel, res) {
                if (res && res == 202) {
                    callback.call();
                }
            }
        });
    },
    deleteProduct: function (productid, callback) {
        if (confirm('确定删除吗？')) {
            var loginid = pageView.getCookieValue('uid');
            var mycart = new MyCart({
                id: 1,
                MemLoginID: loginid,
                ProductGuid: productid
            });

            mycart.url = mycart.urlRoot + loginid + '/' + productid;

            mycart.destroy({
                success: function (model, res) {
                    if (res && res == 200) {
                        callback.call();
                    }
                }
            });
        }
    }
});

